package com.dubito.lucene;

import org.apache.lucene.document.Document;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.*;
import org.apache.lucene.store.FSDirectory;

import java.io.File;
import java.io.IOException;

/**
 * @author liliang
 * @description:
 * @date 2018/4/28.
 */
public class SearcherIndex {

    public static void main(String[] args) throws IOException {

        //创建索引库存储目录
        FSDirectory directory = FSDirectory.open(new File("/Users/liliang/Downloads/index_db"));
        // 创建 IndexReader 对象
        IndexReader indexReader = DirectoryReader.open(directory);
        // 创建IndexSearcher 对象
        IndexSearcher indexSearcher = new IndexSearcher(indexReader);

        // 创建查询对象
         Query query = new TermQuery(new Term("content", "疑"));
        // 调用检索的方法 search(查询对象,查询记录条数);
        TopDocs topDocs = indexSearcher.search(query, 4);
        System.out.println("总命中的记录数:" + topDocs.totalHits);
        System.out.println("最大的分数:" + topDocs. getMaxScore());
        // 获取分数文档数组
        ScoreDoc[] scoreDocs = topDocs.scoreDocs;
        // 迭代
        for (ScoreDoc scoreDoc : scoreDocs) {
            System.out.println("分数:" + scoreDoc.score);
            System.out.println("文档 ID:" + scoreDoc.doc);
            // 获取文档
            Document doc = indexSearcher.doc(scoreDoc.doc);
            System.out.println("id:" + doc.get("id"));
            System.out.println("name:" + doc.get("name"));
            System.out.println("path:" + doc.get("path"));
            System.out.println("content:" + doc.get("fileContent"));
        }
        indexReader.close();
    }
}
